/*****************************************************************************
* Keppe Messenger (KMP) Keppe Project-Team User Messaging System
* Copyright (C) 2013-2014 Keppe Project-Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program.  If not, see <http://www.gnu.org/licenses/>.
*****************************************************************************/

#include "frmChat.h"
#include "frmLogin.h"
#include "ui_frmChat.h"
#include <QDir>
#include <QMenu>
#include <QTime>
#include <QTimer>
#include <QSettings>
QMap<frmChat*,int> cultid;
QMap<frmChat*,QString> cuname;
QMap<frmChat*,QString> cunick;
QMap<frmChat*,QString> culast;
QMap<frmChat*,QString> mynick;
QMap<frmChat*,QString> msglog;
QMap<frmChat*,QSettings*> msgs;
QObject *form;

frmChat::frmChat(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::frmChat)
{
    setWindowFlags(windowFlags()^Qt::WindowContextHelpButtonHint^Qt::WindowMinMaxButtonsHint);
    ui->setupUi(this);
    ui->tbChat->setOpenAutoBrowser(true);
	ui->cmdClose->setVisible(false);
    cultid[this] = 0;
    cuname[this] = "";
    cunick[this] = "";
    culast[this] = "";
    mynick[this] = "";
    QTimer::singleShot(10,this,SLOT(automaticLength()));
}

void frmChat::setForm(frmLogin* login)
{
    form = login;
}

void frmChat::setChatter(QString username, QString nickname, QString userstate, QString myname, bool reloadConf)
{
    this->setWindowTitle(nickname);
    cuname[this] = username;
    cunick[this] = nickname;
    mynick[this] = myname;
    if (reloadConf)
    {
        msgs[this] = new QSettings("Keppe","Keppe Messenger");
        msgs[this]->beginGroup(username);
        msgs[this]->beginGroup("Chat");
        culast[this] = msgs[this]->value("LastMessageFrom","").toString();
        cultid[this] = msgs[this]->value("LastMessageID",0).toInt();
        msgs[this]->endGroup();
        msgs[this]->beginGroup("Messages");
        int beginFrom = 1;
        int workInt = 0;
        bool firstInt = true;
        QStringList emptyList;
        if (cultid[this] > 1000)
        {
            beginFrom = cultid[this] - 1000;
            workInt = beginFrom - 1;
        }
        while(workInt != cultid[this])
        {
            int msgInt = workInt + 1;
            if (firstInt)
            {
                firstInt = false;
                QStringList msg = msgs[this]->value("Message" + QString::number(msgInt),emptyList).toStringList();
                QString message;
                if (msg.length() >= 3)
                {
                    message = msg.at(0);
                    if (msg.at(2) == "false")
                    {
                        QString nick;
                        if (msg.at(1) == "You")
                        {
                            nick = mynick[this];
                            message = "<span style=\"color: grey\">" + nick + "</span><br>" + message;
                        }
                        else if(msg.at(2) == "She/He")
                        {
                            nick = cunick[this];
                            message = "<span style=\"color: blue\">" + nick + "</span><br>" + message;
                        }
                        else
                        {
                            nick = "Unknown";
                            message = "<span style=\"color: red\">" + nick + "</span><br>" + message;
                        }
                    }
                }
                ui->tbChat->append(message);
            }
            else
            {
                QStringList msg = msgs[this]->value("Message" + QString::number(msgInt),emptyList).toStringList();
                QString message;
                if (msg.length() >= 3)
                {
                    message = msg.at(0);
                }
                ui->tbChat->append(message);
            }
            workInt++;
        }
        msgs[this]->endGroup();
    }
    if (userstate.trimmed() == "")
    {
        ui->labChatUname->setText("<span>Chat with </span><span style=\"color: blue;\" title=\"" + username + "\">" + nickname + "</span>");
    }
    else
    {
        ui->labChatUname->setText("<span>Chat with </span><span style=\"color: blue;\" title=\"" + username + "\">" + nickname + "</span><br><span>" + userstate + "</span>");
    }
}

void frmChat::automaticLength()
{
    //ui->txtMessageBox->setMinimumSize(ui->layout1->geometry().width(), 64);
    //QTimer::singleShot(10,this,SLOT(automaticLength()));
}

void frmChat::closeEvent(QCloseEvent *)
{
    msgs[this]->endGroup();
    msgs[this]->deleteLater();
    frmLogin* login = (frmLogin*)form;
    login->removeMe(cuname[this]);
    deleteLater();
}

frmChat::~frmChat()
{
    delete ui;
}

void frmChat::incomingMessage(QString message)
{
    if (culast[this] != "She/He")
    {
        cultid[this]++;
        culast[this] = "She/He";
        QStringList msg;
        msg.append("<span style=\"color: blue\">" + cunick[this] + "</span><br><span>" + convertMessage(message) + "</span>");
        msg.append(culast[this]);
        msg.append("true");
        ui->tbChat->append(msg.at(0));
        msgs[this]->beginGroup("Chat");
        msgs[this]->setValue("LastMessageFrom","She/He");
        msgs[this]->setValue("LastMessageID",cultid[this]);
        msgs[this]->endGroup();
        msgs[this]->beginGroup("Messages");
        msgs[this]->setValue("Message" + QString::number(cultid[this]),msg);
        msgs[this]->endGroup();
    }
    else
    {
        cultid[this]++;
        culast[this] = "She/He";
        QStringList msg;
        msg.append("<span>" + convertMessage(message) + "</span>");
        msg.append(culast[this]);
        msg.append("false");
        ui->tbChat->append(msg.at(0));
        msgs[this]->beginGroup("Chat");
        msgs[this]->setValue("LastMessageFrom","She/He");
        msgs[this]->setValue("LastMessageID",cultid[this]);
        msgs[this]->endGroup();
        msgs[this]->beginGroup("Messages");
        msgs[this]->setValue("Message" + QString::number(cultid[this]),msg);
        msgs[this]->endGroup();
    }
}

QString frmChat::getChatTime()
{
    QString hour;
    QString minute;
    QString second;
    hour = QString::number(QTime::currentTime().hour());
    minute = QString::number(QTime::currentTime().minute());
    second = QString::number(QTime::currentTime().second());
    if (hour.length() == 1) hour = hour.insert(0,"0");
    if (minute.length() == 1) minute = minute.insert(0,"0");
    if (second.length() == 1) second = second.insert(0,"0");
    QString times = "(" + hour + ":" + minute + ")";
    return times;
}

void frmChat::sendMessage()
{
    frmLogin* login = (frmLogin*)form;
    if (login->isConnectedWithServer())
    {
        QString text = QString::fromUtf8(ui->txtMessageBox->text().toUtf8());
        text.replace(QString::fromUtf8("&"),"&amp;");
        text.replace(QString::fromUtf8("<"),"&lt;");
        text.replace(QString::fromUtf8(">"),"&gt;");
        text.replace(QString::fromUtf8("\""),"&quot;");
        text.replace(QString::fromUtf8("ä"),"&auml;");
        text.replace(QString::fromUtf8("ö"),"&ouml;");
        text.replace(QString::fromUtf8("ü"),"&uuml;");
        text.replace(QString::fromUtf8("Ä"),"&Auml;");
        text.replace(QString::fromUtf8("Ö"),"&Ouml;");
        text.replace(QString::fromUtf8("Ü"),"&Uuml;");
        text.replace(QString::fromUtf8("ß"),"&szlig;");
        text.replace(QString::fromUtf8("€"),"&euro;");
        text.replace(QString::fromUtf8("§"),"&sect;");
        text.replace(QString::fromUtf8("©"),"&copy;");
        text.replace(QString::fromUtf8("®"),"&reg;");
        text.replace(QString::fromUtf8("°"),"&deg;");
        text.replace(QString::fromUtf8("²"),"&sup2;");
        text.replace(QString::fromUtf8("³"),"&sup3;");
        text.replace(QString::fromUtf8("\r\n"),"<br>");
        text.replace(QString::fromUtf8("\r"),"<br>");
        text.replace(QString::fromUtf8("\n"),"<br>");
        if (text.trimmed() == QString("")) return;
        int ret = login->sendMessage(cuname[this],text);
        ui->txtMessageBox->clear();
        if (ret == 404 || ret == 1)
        {
            if (culast[this] != "KM")
            {
                culast[this] = "KM";
                QStringList msg;
                msg.append("<span style=\"color: red\">Keppe Messenger</span><br><span>" + cunick[this] + " is offline</span>");
                ui->tbChat->append(msg.at(0));
            }
            else
            {
                culast[this] = "KM";
                QStringList msg;
                msg.append("<span>" + cunick[this] + " is offline</span>");
                ui->tbChat->append(msg.at(0));
            }
        }
        else if (ret == 200)
        {
            if (culast[this] != "You")
            {
                cultid[this]++;
                culast[this] = "You";
                QStringList msg;
                msg.append("<span style=\"color: grey\">" + mynick[this] + "</span><br><span>" + convertMessage(text) + "</span>");
                msg.append(culast[this]);
                msg.append("true");
                ui->tbChat->append(msg.at(0));
                msgs[this]->beginGroup("Chat");
                msgs[this]->setValue("LastMessageFrom","You");
                msgs[this]->setValue("LastMessageID",cultid[this]);
                msgs[this]->endGroup();
                msgs[this]->beginGroup("Messages");
                msgs[this]->setValue("Message" + QString::number(cultid[this]),msg);
                msgs[this]->endGroup();
            }
            else
            {
                cultid[this]++;
                culast[this] = "You";
                QStringList msg;
                msg.append("<span>" + convertMessage(text) + "</span>");
                msg.append(culast[this]);
                msg.append("false");
                ui->tbChat->append(msg.at(0));
                msgs[this]->beginGroup("Chat");
                msgs[this]->setValue("LastMessageFrom","You");
                msgs[this]->setValue("LastMessageID",cultid[this]);
                msgs[this]->endGroup();
                msgs[this]->beginGroup("Messages");
                msgs[this]->setValue("Message" + QString::number(cultid[this]),msg);
                msgs[this]->endGroup();
            }
        }
    }
    else
    {
        ui->txtMessageBox->clear();
        if (culast[this] != "KM")
        {
            culast[this] = "KM";
            QStringList msg;
            msg.append("<span style=\"color: red\">Keppe Messenger</span><br><span>You are offline</span>");
            ui->tbChat->append(msg.at(0));
        }
        else
        {
            culast[this] = "KM";
            QStringList msg;
            msg.append("<span>You are offline</span>");
            ui->tbChat->append(msg.at(0));
        }
    }
}

QString frmChat::convertMessage(QString message)
{
    message = " " + message + " ";
    message = message.replace(QRegExp(" ((?:https?|ftp)://\\S+) "), " <a href=\"\\1\">\\1</a> ");
    message = message.replace(" :) "," <img src=':/img/friendly.png' width='32' height='32'/> ");
    message = message.replace(" :-) "," <img src=':/img/friendly.png' width='32' height='32'/> ");
    message = message.replace(" :| "," <img src=':/img/normal.png' width='32' height='32'/> ");
    message = message.replace(" :-| "," <img src=':/img/normal.png' width='32' height='32'/> ");
    message = message.replace(" :D "," <img src=':/img/laughting.png' width='32' height='32'/> ");
    message = message.replace(" :-D "," <img src=':/img/laughting.png' width='32' height='32'/> ");
    message = message.replace(" :P "," <img src=':/img/haha.png' width='32' height='32'/> ");
    message = message.replace(" :-P "," <img src=':/img/haha.png' width='32' height='32'/> ");
    message = message.replace(" :( "," <img src=':/img/sad.png' width='32' height='32'/> ");
    message = message.replace(" :-( "," <img src=':/img/sad.png' width='32' height='32'/> ");
    message = message.replace(" ;( "," <img src=':/img/cry.png' width='32' height='32'/> ");
    message = message.replace(" ;-( "," <img src=':/img/cry.png' width='32' height='32'/> ");
    message = message.replace(" (cry) "," <img src=':/img/cry.png' width='32' height='32'/> ");
    message = message.replace(" (angry) "," <img src=':/img/angry.png' width='32' height='32'/> ");
    message = message.replace(" (evil) "," <img src=':/img/evil.png' width='32' height='32'/> ");
    message = message.trimmed();
    return message;
}

void frmChat::on_txtMessageBox_returnPressed()
{
    sendMessage();
}

void frmChat::on_cmdSmiley_clicked()
{
    QMenu *smileyContext = new QMenu();
    QAction *evilSmiley = smileyContext->addAction(QIcon(":/img/evil.png"),"(evil)");
    connect(evilSmiley,SIGNAL(triggered()),this,SLOT(addEvilSmiley()));
    QAction *friendlySmiley = smileyContext->addAction(QIcon(":/img/friendly.png"),":)");
    connect(friendlySmiley,SIGNAL(triggered()),this,SLOT(addFriendlySmiley()));
    QAction *laughtingSmiley = smileyContext->addAction(QIcon(":/img/laughting.png"),":D");
    connect(laughtingSmiley,SIGNAL(triggered()),this,SLOT(addLaughtingSmiley()));
    QAction *hahaSmiley = smileyContext->addAction(QIcon(":/img/haha.png"),":P");
    connect(hahaSmiley,SIGNAL(triggered()),this,SLOT(addHahaSmiley()));
    QAction *normalSmiley = smileyContext->addAction(QIcon(":/img/normal.png"),":|");
    connect(normalSmiley,SIGNAL(triggered()),this,SLOT(addNormalSmiley()));
    QAction *sadSmiley = smileyContext->addAction(QIcon(":/img/sad.png"),":(");
    connect(sadSmiley,SIGNAL(triggered()),this,SLOT(addSadSmiley()));
    QAction *angrySmiley = smileyContext->addAction(QIcon(":/img/angry.png"),"(angry)");
    connect(angrySmiley,SIGNAL(triggered()),this,SLOT(addAngrySmiley()));
    QAction *crySmiley = smileyContext->addAction(QIcon(":/img/cry.png"),"(cry)");
    connect(crySmiley,SIGNAL(triggered()),this,SLOT(addCrySmiley()));
    smileyContext->popup(QCursor::pos());
}

void frmChat::appendTextToLineEdit(QLineEdit *lineedit, QString text)
{
    QString ntext = lineedit->text();
    ntext = ntext + text;
    lineedit->setText(ntext);
    lineedit->setFocus();
}

void frmChat::addEvilSmiley()
{
    appendTextToLineEdit(ui->txtMessageBox," (evil) ");
}

void frmChat::addFriendlySmiley()
{
    appendTextToLineEdit(ui->txtMessageBox," :) ");
}

void frmChat::addLaughtingSmiley()
{
    appendTextToLineEdit(ui->txtMessageBox," :D ");
}

void frmChat::addHahaSmiley()
{
    appendTextToLineEdit(ui->txtMessageBox," :P ");
}

void frmChat::addNormalSmiley()
{
    appendTextToLineEdit(ui->txtMessageBox," :| ");
}

void frmChat::addSadSmiley()
{
    appendTextToLineEdit(ui->txtMessageBox," :( ");
}

void frmChat::addAngrySmiley()
{
    appendTextToLineEdit(ui->txtMessageBox," (angry) ");
}

void frmChat::addCrySmiley()
{
    appendTextToLineEdit(ui->txtMessageBox," (cry) ");
}

void frmChat::on_cmdSend_clicked()
{
    sendMessage();
}

void frmChat::on_cmdClose_clicked()
{
    this->close();
}
